package com.wm.blog_config.util;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.IOUtils;
import com.wm.blog_common.result.Result;
import com.wm.blog_config.config.QiNiuProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * @author ：半卷流年
 * @description : 七牛云工具类
 * @createTime ：2020/6/9
 */
@Slf4j
@Component
public class QiNiuUtil {

    private QiNiuUtil(){}

    @Autowired
    private QiNiuProperties qiNiuProperties;

    private static QiNiuUtil qiNiuUtil;

    @PostConstruct
    public void init() {
        qiNiuUtil = this;
    }

    public static Result<String> uploadFile(InputStream inputStream) {
        //构造一个带指定 Region 对象的配置类,指定区域
        Configuration cfg = new Configuration(Region.region2());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        try {
            //流转为byte字节数组
            byte[] uploadBytes = IOUtils.toByteArray(inputStream);
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(qiNiuUtil.qiNiuProperties.getAccessKey(), qiNiuUtil.qiNiuProperties.getSecretKey());
            String upToken = auth.uploadToken(qiNiuUtil.qiNiuProperties.getBucket());
            Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);
            String url = qiNiuUtil.qiNiuProperties.getShowPrefix() + "/" +  putRet.key;
            log.info("上传七牛云返回值:{}", JSONObject.toJSONString(putRet));
            return Result.success(url);
        } catch (Exception ex) {
            log.error("上传七牛云失败:{}", ex.getMessage(), ex);
            return Result.failure();
        }
    }

    /**
     * 删除文件
     *
     * @return
     */
    public static Result deleteFile(String fileKey) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //...其他参数参考类注释
        Auth auth = Auth.create(qiNiuUtil.qiNiuProperties.getAccessKey(), qiNiuUtil.qiNiuProperties.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(qiNiuUtil.qiNiuProperties.getBucket(), fileKey);
            return Result.success();
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            log.error("七牛云上传文件异常:{}", ex.getMessage(), ex);
            return Result.failure();
        }
    }

}
